﻿using System.IO;
using System.IO.IsolatedStorage;
using BattlelogMobile.Core.Model;

namespace BattlelogMobile.Core.Repository
{
    public class FileCredentialsRepository : ICredentialsRepository 
    {
        public FileCredentialsRepository() : this(IsolatedStorageFile.GetUserStoreForApplication())
        {}

        public FileCredentialsRepository(IsolatedStorageFile storageFile)
        {
            StorageFile = storageFile;
        }

        public IsolatedStorageFile StorageFile { get; set; }

        public void Save(ICredentials credentials)
        {
            using (var writer = new StreamWriter(StorageFile.OpenFile(Common.CredentialsFile, FileMode.OpenOrCreate, FileAccess.Write)))
            {
                writer.WriteLine(credentials.ToString());
                writer.Close();
            }
        }

        public ICredentials Load()
        {
            ICredentials credentials = new Credentials();
            using (var reader = new StreamReader(StorageFile.OpenFile(Common.CredentialsFile, FileMode.OpenOrCreate, FileAccess.Read)))
            {
                if (reader.Peek() > 0)
                {
                    credentials.Email = reader.ReadLine();
                    credentials.Password = reader.ReadLine();
                    credentials.RememberMe = System.Convert.ToBoolean(reader.ReadLine());
                }
                reader.Close();
            }
            return credentials;
        }
    }
}
